package com.tools.handler.analysis;

import com.tools.common.result.Result;
import com.tools.handler.StepHandler;
import com.tools.pojo.test.AnalysisResult;
import com.tools.pojo.workflow.bo.StepContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 分支决策步骤处理类
 */
@Slf4j
@Component
public class BranchDecisionStepHandler implements StepHandler {

    private static final String STEP_CODE = "BRANCH_DECISION";
    private final ExpressionParser expressionParser = new SpelExpressionParser();

    @Override
    public String getStepCode() {
        return STEP_CODE;
    }

    /**
     * 执行分支决策步骤
     */
    @Override
    public Result<?> execute(StepContext context) {
        try {
            log.info("开始执行分支决策步骤，流程实例ID: {}", context.getFlowInstanceId());

            // 获取分析结果
            AnalysisResult analysisResult = context.getContextData("analysisResult", AnalysisResult.class);
            if (analysisResult == null) {
                return Result.fail("未找到分析结果，无法进行分支决策");
            }

            // 获取分支条件配置
            List<Map<String, Object>> conditions = (List<Map<String, Object>>) context.getStepConfig().get("conditions");
            if (conditions == null || conditions.isEmpty()) {
                return Result.fail("未找到分支条件配置");
            }

            // 评估条件并决定下一步
            String nextStep = evaluateConditions(conditions, analysisResult, context);

            // 将决策结果存入上下文
            context.putContextData("nextStep", nextStep);
            context.putContextData("branchDecisionTime", System.currentTimeMillis());

            log.info("分支决策完成，下一步骤: {}", nextStep);
            return Result.success("分支决策完成", nextStep);

        } catch (Exception e) {
            log.error("分支决策步骤执行失败", e);
            return Result.fail("分支决策失败: " + e.getMessage());
        }
    }

    /**
     * 评估分支条件
     */
    private String evaluateConditions(List<Map<String, Object>> conditions,
                                      AnalysisResult analysisResult, StepContext context) {
        // 创建SPEL评估上下文
        StandardEvaluationContext spelContext = new StandardEvaluationContext();
        spelContext.setVariable("analysisResult", analysisResult);
        spelContext.setVariable("context", context.getContextData());

        // 按顺序评估条件
        for (Map<String, Object> condition : conditions) {
            String conditionExpr = (String) condition.get("condition");
            String nextStep = (String) condition.get("nextStep");
            String description = (String) condition.get("description");

            // 默认分支
            if ("default".equals(conditionExpr)) {
                log.info("选择默认分支: {} - {}", nextStep, description);
                return nextStep;
            }

            // 评估条件表达式
            try {
                Expression expression = expressionParser.parseExpression(conditionExpr);
                Boolean result = expression.getValue(spelContext, Boolean.class);

                if (Boolean.TRUE.equals(result)) {
                    log.info("条件满足: {} -> {} - {}", conditionExpr, nextStep, description);
                    return nextStep;
                }
            } catch (Exception e) {
                log.warn("条件表达式评估失败: {}, 错误: {}", conditionExpr, e.getMessage());
            }
        }

        // 如果没有条件满足且没有默认分支，返回第一个条件的分支
        String defaultNextStep = (String) conditions.get(0).get("nextStep");
        log.warn("所有条件评估失败，使用第一个分支作为默认: {}", defaultNextStep);
        return defaultNextStep;
    }

}
